﻿using Microsoft.AspNetCore.Http;
using System;
using System.Text;

namespace FurStudy.Core
{
    /// <summary>
    /// 会话和状态管理类
    /// </summary>
    public class SessionStateManagement
    {
        private readonly HttpContext _httpContext;

        public SessionStateManagement(HttpContext httpContext)
        {
            _httpContext = httpContext;
        }

        /// <summary>
        /// Cookie使用
        /// </summary>
        public void CookieDemo()
        {
            // 读取 Cookies
            var value = _httpContext.Request.Cookies["key"]; // httpContext可以通过IHttpContextAccessor获取，也可以通过App.HttpContext获取

            // 设置 Cookies
            string key = "xxxxxxxxxxxxx"; // 测试key
            var option = new CookieOptions();
            option.Expires = DateTime.Now.AddMilliseconds(10);
            _httpContext.Response.Cookies.Append(key, value, option);

            // 删除 Cookies
            _httpContext.Response.Cookies.Delete(key);
        }

        /// <summary>
        /// Session使用
        /// </summary>
        public void SessionDemo()
        {
            // 读取 Session
            var byteArr = _httpContext.Session.Get("key"); // 返回 byte[]
            var str = _httpContext.Session.GetString("key");   // 返回 string[]
            var num = _httpContext.Session.GetInt32("key");    // 返回 int

            // 设置 Session
            _httpContext.Session.SetString("key", "value");  // 设置字符串
            _httpContext.Session.SetInt32("key", 1); // 设置 int 类型
        }

        /// <summary>
        /// QueryString使用
        /// </summary>
        public void QueryStringDemo()
        {
            // 获取值
            var str = _httpContext.Request.Query["key"];
        }

        /// <summary>
        /// HttpContext.Items使用
        /// </summary>
        public void HttpContextItemsDemo()
        {
            // 读取
            var value = _httpContext.Items["key"];
            // 添加
            _httpContext.Items["key"] = "任何值包括对象";
            // 删除
            _httpContext.Items.Remove("key");
        }

        // Cache方式：第14节分布式缓存已讲过
    }
}
